import { useState, useEffect } from 'react'
import { Checkbox, Popover, message } from 'antd'
import { cloneDeep } from 'lodash';
import CommonModal from '@/components/CommonModal'
import CommonLoading from '@/components/CommonLoading';
import { platformTypeName } from '@/utils/config';
import { batchSyncFaceSheetOp } from '../service';
import styles from '../index.module.less'

//同步弹窗
 const MarkUnusalModal = ({ type, visible, shopList, handleOk, handleCancel }) => {

   const [loading, setLoading] = useState(false);//loading
   const [list, setList] = useState([]);
   const [hasChecked, setChecked] = useState(true);


   useEffect(()=>{
     const time_num = new Date().getTime();
     const arr = []
     shopList.map(item=>{
       if(item.authExpireTime && item.authExpireTime * 1000 > time_num){
         arr.push({...item,checked:true})
       }
     })
     setList(arr)
   },[visible])

   useEffect(()=> {
    const bool = list.some(item => item.checked);
    if(bool){
      setChecked(true)
    }else{
      setChecked(false)
    }
   },[list])

  const onOk = async () => {
    const hasChecked = list.some(item => item.checked)
    if(hasChecked){
      const arr = [];
      list.map(item=>{
        if(item.checked){
          arr.push({
            ecstoreId:item.id,
            ecstoreName:item.storeName,
            type
          })
        }
      })
       setLoading(true)
       const { msg, success } = await batchSyncFaceSheetOp({
        parameters:arr
       })
       if(success){
         message.success(msg);
         handleOk();
         onCancel();
       }
       setLoading(false)
    }else{
      message.info('请至少选择1个网店')
    }
  }

  const onCancel = () => {
    handleCancel();
    setList([]);
  }

  const handleChange = (val, index) => {
    const arr = cloneDeep(list)
    arr[index]["checked"] = val;
    setList(arr)
  }

  return (
    <CommonModal
       title='同步已开通的电子面单服务'
       visible={visible}
       onOk={onOk}
       onCancel={onCancel}
    >
      <div className='lable-require' style={{fontWeight:'bold', marginBottom:'8px'}}>选择需要同步面单的网店：</div>
      <div className={styles.modalWrapper}>
         { list.map((item,index)=>{
           return  <div className={styles.itemBox} key={item.id}>
              <Checkbox checked={item.checked} onChange={(e)=>handleChange(e.target.checked,index)}/>&nbsp;&nbsp;
              <Popover content={(<div className='custom-ant-popver-content'>{item.storeName}-{platformTypeName[item.type]}</div>)}>
               <span className='textOverflowMultiTwo' style={{cursor:'pointer'}}>{item.storeName}-{platformTypeName[item.type]}</span>
              </Popover>
            </div>
         })}
      </div>
      { !hasChecked && <div className='common-color9' style={{margin:'6px 0 0 24px'}}>至少选择1个网店</div> }
      <CommonLoading loading={loading} />
    </CommonModal>
  )
}

export default MarkUnusalModal